/*
 * @Author: icymoon911 icymoon911@163.com
 * @Date: 2024-08-19 11:37:38
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-08-26 15:06:04
 * @FilePath: \webapp\api\service.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
var config = {
  usdt_url: 'http://45.207.61.157:9700',
  usdt_token: 'epusdt_password_dfhjfdjyhDSARFESDposa',
};

import axios from 'axios';
import md5 from 'md5';
import cryptoJS from 'crypto-js';
// const cryptoJS = require('crypto-js'); // Import encryption modules for subsequent encryption calculations
// const { Web3 } = require('web3'); // Import the Web3 library for interacting with Ethereum

const apiBaseUrl = 'https://www.okx.com'; // Define the underlying path of the request
const web3RpcUrl = 'https://.....pro'; // The URL for the Ethereum node you want to connect to
const privateKey = '0x...xxx'; // Set the private key of your wallet (replace '0x...xxx' with your actual private key). NEVER SHARE THIS WITH ANYONE!
const chainId = '1';
const fromTokenAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';    // Native token address
const toTokenAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7';

const userWalletAddress = '0x...35'; // User wallet address
const secretKey = 'BE9C873D78ECADA41DB665039005D7A4'; // The key obtained from the previous application
const apiKey = 'aa479eb4-bdb9-4bb0-8adf-bf12f8541813'; // The api Key obtained from the previous application
const passphrase = 'Killyou91111!'; // The password created when applying for the key
const date = new Date(); // Get the current time
const timestamp = date.toISOString(); // Convert the current time to the desired format
// const web3 = new Web3(new Web3.providers.HttpProvider(web3RpcUrl)); //Establishing web3 link

const URL = {
  createTransaction: config.usdt_url + '/api/v1/order/create-transaction', // POST 创建交易
  supportedChains: apiBaseUrl + '/api/v5/waas/wallet/chain/supported-chains',
  getCurrentPrice: apiBaseUrl + '/api/v5/waas/wallet/token/current-price',

  getAllCoins: apiBaseUrl + '/api/v5/waas/asset/get-all-coins',
};

const getRequestUrl = (apiBaseUrl, api, queryParams) => {
  return apiBaseUrl + api + '?' + new URLSearchParams(queryParams).toString();
};
// const apiRequestUrl = getRequestUrl(apiBaseUrl, '/swap', swapParams);

const headersParams = {
  'Content-Type': 'application/json',
  'OK-ACCESS-KEY': apiKey,
  'OK-ACCESS-SIGN': cryptoJS.enc.Base64.stringify(
    cryptoJS.HmacSHA256(timestamp + 'GET' + '/api/v5/dex/aggregator/xxx?xxx=xxx', secretKey)
  ),
  'OK-ACCESS-TIMESTAMP': timestamp,
  'OK-ACCESS-PASSPHRASE': passphrase,
  'OK-ACCESS-PROJECT': 'note-bot'
};

function getHeadersParams(method, url) {
  return {
    // ...headersParams,
    // 'OK-ACCESS-SIGN': cryptoJS.enc.Base64.stringify(
    //     cryptoJS.HmacSHA256(timestamp + method.toLocaleUpperCase() + url.replace(apiBaseUrl, ''), secretKey)
    // ),
    'Content-Type': 'application/json',
    'OK-ACCESS-KEY': apiKey,
    'OK-ACCESS-SIGN': cryptoJS.enc.Base64.stringify(
      cryptoJS.HmacSHA256(timestamp + method.toLocaleUpperCase() + url.replace(apiBaseUrl, ''), secretKey)
    ),
    'OK-ACCESS-TIMESTAMP': timestamp,
    'OK-ACCESS-PASSPHRASE': passphrase,
    'OK-ACCESS-PROJECT': 'note-bot'
  }
}

/**
 * 创建交易
 * https://github.com/assimon/epusdt/blob/master/wiki/API.md
 * @param {Object} data 创建交易参数 
 * {
    "order_id": "2022123321312321321",
    "amount": 100,
    "notify_url": "http://example.com/",
    "redirect_url": "http://example.com/",
    "signature": "xsadaxsaxsa"
    }
    请求参数
        名称	位置	类型	必选	中文名	说明
        body	body	object	否		
        » order_id	body	string	是	请求支付订单号	
        » amount	body	number	是	支付金额(CNY)	小数点保留后2位，最少0.01
        » notify_url	body	string	是	异步回调地址	
        » redirect_url	body	string	否	同步跳转地址	
        » signature	body	string	是	签名	接口统一加密方式
 * @returns {Promise}
 */
export function createTransaction(data) {
  const sortParams = Object.keys(data).sort((k1, k2) => k1.localeCompare(k2)).map(key => (`${key}=${data[key]}`));

  const waitEncry = sortParams.join('&') + config.usdt_token;

  const md5Encry = md5(waitEncry);

  return axios({
    url: URL.createTransaction,
    method: "post",
    data: {
      ...data,
      signature: md5Encry, // 签名
    },
  });
}

export function supportedChains() {
  const method = 'get';

  // return axios({
  //     url: URL.supportedChains,
  //     method,
  //     // headers: getHeadersParams(method, URL.supportedChains),
  // });
  return axios.get(URL.supportedChains, {
    headers: getHeadersParams(method, URL.supportedChains),
  });
}

export function getCurrentPrice(data) {
  const method = 'post';

  return axios({
    url: URL.getCurrentPrice,
    method,
    headers: getHeadersParams(method, URL.getCurrentPrice),
    data: data,
  });
}


export function getAllCoins() {
  const method = 'get';

  // return axios({
  //     url: URL.supportedChains,
  //     method,
  //     // headers: getHeadersParams(method, URL.supportedChains),
  // });
  return axios.get(URL.getAllCoins, {
    // headers: getHeadersParams(method, URL.supportedChains),
  });
}
